/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pv168.uloha3.swing.workers;

import cz.muni.fi.pv168.uloha3.common.DBUtils;
import cz.muni.fi.pv168.uloha3.entities.Owner;
import cz.muni.fi.pv168.uloha3.exceptions.OwnerManagerException;
import cz.muni.fi.pv168.uloha3.managers.OwnerManager;
import cz.muni.fi.pv168.uloha3.managers.impl.OwnerManagerImpl;
import cz.muni.fi.pv168.uloha3.swing.OwnersTableModel;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.DataSource;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;

/**
 *
 * @author stefan
 */
public class OwnerEditSwingWorker extends SwingWorker<Boolean, Void> {

    private final String id;
    private final String name;
    private final String surname;
    private final String address;
    private final String ssn;
    private final String telephone;
    private final OwnersTableModel model;

    public OwnerEditSwingWorker(String id, String name, String surname, String address, String ssn, String telephone, OwnersTableModel model) {
        this.id = id;
        this.name = name;
        this.surname = surname;
        this.address = address;
        this.ssn = ssn;
        this.telephone = telephone;
        this.model = model;
    }

    @Override
    protected Boolean doInBackground() throws Exception {
        
        DataSource dataSource = DBUtils.initConnector();
        
        OwnerManager managerOwner = new OwnerManagerImpl();
        managerOwner.setDataSource(dataSource);
        
        Owner owner = new Owner();
        owner.setId(new Long(id));
        owner.setFirstName(name);
        owner.setLastName(surname);
        owner.setAddress(address);
        owner.setSsn(ssn);
        owner.setTelephone(telephone);
        
        try {
            managerOwner.editOwner(owner);
        } catch (OwnerManagerException ex) {
            
            Logger.getLogger(OwnerEditSwingWorker.class.getName()).log(Level.WARNING, ex.getMessage());
            JOptionPane.showMessageDialog(null, "Owner could not be updated (" + ex.getMessage() + ")");
            return false;
        }

        model.updateOwner(owner);
        JOptionPane.showMessageDialog(null, "Owner updated");
        return true;
    }
}
